#!/bin/bash -e
#
#

WORK_DIR=${WORK_DIR:-`cd ${0%/*};pwd`}

#######################################
# Cleanup files from the backup dir
# Globals:
#   BACKUP_DIR
#   ORACLE_SID
# Arguments:
#   None
# Returns:
#   None
#######################################
gen_proto_files() {
#  shopt -s globstar
  local proto_files=${WORK_DIR}/**/*.proto
  local proto_folders=()
  for file_name in ${proto_files}; do
    proto_folders+=(${file_name%/*\.proto})
  done

  folders=($(echo "${proto_folders[@]}" | tr ' ' '\n' | sort -u | tr '\n' ' '))
  echo "${folders[@]}"
#  shopt -u globstar
}

generate_protobuf_stub() {
  folders=($(gen_proto_files))
  # shellcheck disable=SC2068
  for folder in ${folders[@]}; do
    GEN_GO_COMMAND="--go_out=${folder} --go_opt=paths=source_relative"
    GEN_GRPC_COMMAND="--go-grpc_out=${folder} --go-grpc_opt=require_unimplemented_servers=false,paths=source_relative"
    GEN_GATEWAY_COMMAND="--grpc-gateway_out=${folder} --grpc-gateway_opt=paths=source_relative"
    local gateway_command="${GEN_GATEWAY_COMMAND},grpc_api_configuration=${folder}/service.yaml"
    command_str="protoc ${GEN_GO_COMMAND} ${GEN_GRPC_COMMAND} ${gateway_command} ${folder}/*.proto -I${folder} -I."
    $command_str
  done
}

generate_protobuf_stub
